package com.ys.ylideas.controller;

import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.ylideas.YlIdeasApplication;
import com.ys.ylideas.entity.BaiProject;
import com.ys.ylideas.entity.BaiUserContact;
import com.ys.ylideas.entity.IdeaEntity;
import com.ys.ylideas.entity.UserEntity;
import com.ys.ylideas.entity.UserInfo;
import com.ys.ylideas.service.AccountService;
import com.ys.ylideas.util.CommonData;
import com.ys.ylideas.util.GetHttpJsonobject;
import com.ys.ylideas.util.HttpRequest;
import com.ys.ylideas.util.R;
import com.ys.ylideas.util.TimeUtil;

@RestController
public class HelpController {

	private UserInfo userInfo;

	@Autowired
	private AccountService accountService;
	
	private static final Logger logger = LoggerFactory.getLogger(YlIdeasApplication.class);
	
	private static final String CANNOT_GET_ACCESS_TOKEN = "CANNOT_GET_ACCESS_TOKEN";

	/**
	 * 从配置文件中读取
	 */
	@ModelAttribute
	public void setUp() {
		Properties prop = new Properties();
		try {
			prop.load(HelpController.class.getClassLoader().getResourceAsStream("baidu-app.properties"));

			userInfo = new UserInfo();
			userInfo.setClientId(prop.getProperty("clientId"));
			userInfo.setClientSecret(prop.getProperty("clientSecret"));
			userInfo.setGrantType(prop.getProperty("grantType"));
			userInfo.setRedirect_uri(prop.getProperty("redirect_uri"));
			userInfo.setUri(prop.getProperty("uri"));

			

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	  @PostMapping("/getUserKeyword")
	  public R getCode(HttpServletRequest request) throws Exception {
		  UserEntity userEntity = (UserEntity) request.getSession().getAttribute("User");
		  String accessToken = (String) request.getSession().getAttribute("access_token");
	      Map<Long, String> baiProject = HttpRequest.getUserKeywords(accessToken,request.getSession());
	      Map<String, Object> map = new HashMap<>();
	      map.put("username", userEntity.getUserName());
	      map.put("getUserKeyword", baiProject);
	      return R.ok(map);      
	  }

	@RequestMapping("/")
	public ModelAndView toLanding(@RequestParam Map<String, Object> params,HttpServletRequest request) {
		String authCode = (String) params.get("code");
		String mavUrl = "redirect:page/landing.html?code=";
		ModelAndView mav;
    	String url = userInfo.getUri() + "?client_id=" + userInfo.getClientId() + "&client_secret="
	          + userInfo.getClientSecret() + "&grant_type=" + userInfo.getGrantType() + "&code=" + authCode
	          + "&redirect_uri=" + userInfo.getRedirect_uri();
    	JSONObject jsonObject = new JSONObject();
    	UserEntity userEntity = new UserEntity();
    	jsonObject = GetHttpJsonobject.httpsRequest(url, "POST", null);
    	String accessToken = jsonObject.getString("access_token");
    	if (accessToken == null||accessToken =="") {
    		mav = new ModelAndView(mavUrl+CANNOT_GET_ACCESS_TOKEN);
    		return mav;
    	}
    	
    	JSONObject userInfo = HttpRequest.getAccountInfo(accessToken);
    	String userBody = userInfo.getString("body");
    	String userData = JSONObject.parseObject(userBody).getString("data");
    	//logger.debug(userData);
    	JSONArray userInfos = JSONArray.parseArray(userData);
    	long userId = userInfos.getJSONObject(0).getInteger("userId");
    	String refresh_token = jsonObject.getString("refresh_token");
    	String username = jsonObject.getString("username");
	
    	userEntity.setUserId(userId);
	    userEntity.setUserName(username);
	    userEntity.setRefreshToken(refresh_token);

	    List<UserEntity> isHadAccount = accountService.checkAccount(userId);
	    if (isHadAccount.size() <= 0) {
	    	userEntity.setCreateTime(TimeUtil.getTime());
	    	userEntity.setRecentTime(TimeUtil.getTime());
	    	userEntity.setCountVisit(1);
	    	accountService.save(userEntity);
	    } else {
	    	userEntity.setRecentTime(TimeUtil.getTime());
	    	accountService.update(userEntity);
	    }
	    userEntity.setRefreshToken(null);
	    HttpSession session =request.getSession();
	    session.setAttribute("User", userEntity);
	    session.setAttribute("access_token", accessToken);
    	mav = new ModelAndView(mavUrl+authCode);
		return mav;
	}

	
	@RequestMapping("/getSession")
	public R getSession(@RequestBody Map<String,Object> jsonData,HttpServletRequest request) {
		int code = -1;
		Long params = 0L;
		HttpSession httpSession = request.getSession();
		if(jsonData.get("code")!=null){
			code = Integer.parseInt(jsonData.get("code").toString());
		}
		if (jsonData.get("param")!=null) {
			params = Long.parseLong(jsonData.get("param").toString());
		}
		 
		if (code == 0) {
			UserEntity userEntity = (UserEntity) httpSession.getAttribute("User");
			if(userEntity!=null){
				return R.ok().put("identifier", userEntity.getUserId());
			}else{
				return R.ok().put("identifier", "404");
			}
		}else if (code == 1) {
			Map<Long, List<Map<Long, String>>> camAdgMap = (Map<Long, List<Map<Long, String>>>) httpSession.getAttribute("camAdgMap");
			if(camAdgMap!=null&&params!=0L){
				return R.ok().put("identifier", camAdgMap.get(params));
			}else if(camAdgMap!=null&&params == 0L){
				return R.ok().put("identifier", camAdgMap);
			}else{
				return R.ok().put("identifier", "404");
			}
		}else if(code == 2) {
			Map<Long, List<Map<Long, String>>> adgKyMap = (Map<Long, List<Map<Long, String>>>) httpSession.getAttribute("adgKyMap");
			if(adgKyMap!=null&&params!=0L){
				return R.ok().put("identifier", adgKyMap.get(params));
			}else if(adgKyMap!=null&&params == 0L){
				return R.ok().put("identifier", adgKyMap);
			}else{
				return R.ok().put("identifier", "404");
			}
		}else {
			return R.ok().put("identifier", "404");
		}
	}
	
	@RequestMapping("/sendIdentify")
	public R sendIdentify(HttpServletRequest request) {
		String phoneNumber = request.getParameter("jsPhone");
		String url = "http://localhost:20171/simi/yuanshengSimi.do?sendBaiduAppSms";
		JSONObject params2 = new JSONObject();
		params2.put("mobile_num", phoneNumber);
		JSONObject totalJson = new JSONObject();
		JSONObject response = GetHttpJsonobject.httpPOST(url, "mobile_num=" + phoneNumber + "&type=4&appname='原力创意'");
		// {"msg":"send success","success":true,"jsonStr":"{\"msg\":\"send
		// success\",\"success\":true,\"attributes\":{\"smscode\":\"322626\"}}","attributes":{"smscode":"322626"}}
		response = JSONObject.parseObject(response.getString("attributes"));
		
		long identify = Long.valueOf(response.getString("smscode"));

		if (identify > 0) {
			HttpSession session = request.getSession();
			session.setAttribute("identify", identify);
			return R.ok().put("result", "success");
		}
		return R.ok().put("result", "error");
	}
	
	@RequestMapping("/checkIdentify")
	public R checkIdentify(HttpServletRequest request) {
		HttpSession session = request.getSession();

		long jsIdentify = Long.valueOf(request.getParameter("jsVerification"));
		long identify = Long.valueOf(session.getAttribute("identify").toString());
		if (jsIdentify == identify) {
			session.setAttribute("identify", null);
			return R.ok().put("result", "success");
		}
		return R.ok().put("result", "error");
	}
	
	@RequestMapping("/showIndex")
	public ModelAndView showIndex(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("index.html");
		BaiUserContact baiUserContact = new BaiUserContact();
	    HttpSession session =request.getSession(false);
		UserEntity userEntity = (UserEntity) session.getAttribute("User");
		String phone = request.getParameter("jsPhone");
		if (userEntity.getUserId() != 0 && phone != null) {
			baiUserContact.setUserId(userEntity.getUserId());
			baiUserContact.setAppId(CommonData.APP_ID);
			baiUserContact.setCompany_name(userEntity.getUserName());
			baiUserContact.setCreateTime(new Date());
			baiUserContact.setVisitTime(new Date());
			baiUserContact.setPhone_number(phone);
			// 执行插入
			boolean result = accountService.saveForService(baiUserContact);
			if (result) {
				return mav;
			}

		}
		return null;
	}
	
	
	


}
